﻿using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;

namespace MijnMultiOSRSSApp.Common.Helpers
{
    public class Storage
    {
        public static void Clear(string key)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(key))
                PhoneApplicationService.Current.State.Remove(key);
        }

        public static void Save(string key, object value)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(key))
                PhoneApplicationService.Current.State.Remove(key);

            PhoneApplicationService.Current.State.Add(key, value);
        }

        public static T Load<T>(string key)
        {
            object result;

            if (!PhoneApplicationService.Current.State.TryGetValue(key, out result))
                result = default(T);

            return (T)result;
        }

        public static bool ClearPersistent(string key)
        {
            if (null == key)
                return false;

            var store = IsolatedStorageSettings.ApplicationSettings;
            if (store.Contains(key))
                store.Remove(key);
            store.Save();
            return true;
        }

        public static bool SavePersistent(string key, object value)
        {
            if (null == value)
                return false;

            var store = IsolatedStorageSettings.ApplicationSettings;
            if (store.Contains(key))
                store[key] = value;
            else
                store.Add(key, value);

            store.Save();
            return true;
        }

        public static T LoadPersistent<T>(string key)
        {
            var store = IsolatedStorageSettings.ApplicationSettings;
            if (!store.Contains(key))
                return default(T);

            return (T)store[key];
        }
    }
}
